<template>
  <a-card 
    :title="project.name" 
    :bordered="true"
    class="project-card"
    :hoverable="true"
  >
    <template #extra>
      <div v-if="isAdmin" class="action-buttons">
        <a-button 
          type="link" 
          size="small" 
          @click="onEdit"
          :icon="h(EditOutlined)"
        >
          编辑
        </a-button>
        <a-popconfirm
          title="确定要删除这个项目吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onDelete"
        >
          <a-button 
            type="link" 
            size="small" 
            danger
            :icon="h(DeleteOutlined)"
          >
            删除
          </a-button>
        </a-popconfirm>
      </div>
    </template>

    <div class="project-description">
      {{ project.description || '暂无描述' }}
    </div>

    <div class="project-group" v-if="group">
      <a-tag color="blue">{{ group.name }}</a-tag>
    </div>

    <div class="environments-section">
      <h4>环境配置</h4>
      <div class="environments-list">
        <div 
          v-for="environment in project.environments" 
          :key="environment.id"
          class="environment-item"
        >
          <div class="environment-info">
            <span class="environment-name">{{ environment.name }}</span>
            <a-tag 
              :color="getEnvironmentTypeColor(environment.type)"
              size="small"
            >
              {{ getEnvironmentTypeName(environment.type) }}
            </a-tag>
          </div>
          
          <div class="environment-hosts" v-if="environment.hosts.length > 0">
            <div 
              v-for="host in environment.hosts" 
              :key="host"
              class="host-item"
            >
              <a-tag size="small" style="word-break: break-all; white-space: normal; height: auto; max-width: 100%; line-height: 1.5;">{{ host }}</a-tag>
            </div>
          </div>

          <div class="environment-control">
            <a-switch
              :checked="activeEnvironments.includes(environment.id)"
              :loading="switchLoading[environment.id]"
              @change="(checked: boolean) => onEnvironmentToggle(environment.id, checked, environment.type)"
              :disabled="!isAdmin"
            />
            <span class="switch-label">
              {{ environment.isActive ? '已激活' : '未激活' }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { ref, h } from 'vue';
import { message } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import type { ProjectCardProps, EnvironmentType } from '@/types';
import { projectApi } from '@/api';
import { storageManager } from '@/utils/storage';

// Props
const props = defineProps<ProjectCardProps>();

// Emits
const emit = defineEmits<{
  edit: [projectId: string];
  delete: [projectId: string];
  refresh: [];
  environmentChange: [envId: string, checked: boolean, envType: EnvironmentType];
}>();

const activeEnvironments = ref<string[]>([]);
// 响应式数据
const switchLoading = ref<Record<string, boolean>>({});

// 监听父组件传递的环境变化，实时更新开关状态
const updateActiveEnvironments = () => {
  activeEnvironments.value = storageManager.getActiveEnvironments();
};

// 暴露方法给父组件调用
defineExpose({
  updateActiveEnvironments
});

// 环境类型颜色映射
const environmentTypeColors: Record<EnvironmentType, string> = {
  development: 'green',
  test: 'orange',
  preview: 'purple',
  production: 'red',
  custom: 'blue',
};

// 环境类型名称映射
const environmentTypeNames: Record<EnvironmentType, string> = {
  development: '开发环境',
  test: '测试环境',
  preview: '预发布环境',
  production: '正式环境',
  custom: '自定义环境',
};

// 获取环境类型颜色
const getEnvironmentTypeColor = (type: EnvironmentType): string => {
  return environmentTypeColors[type] || 'default';
};

// 获取环境类型名称
const getEnvironmentTypeName = (type: EnvironmentType): string => {
  return environmentTypeNames[type] || '未知环境';
};

// 环境开关切换处理 (智能互斥激活版)
const onEnvironmentToggle = async (id: string, checked: boolean, envType: EnvironmentType) => {
  if (checked) {
    // 激活环境时，使用智能互斥逻辑
    // 获取所有环境信息以支持自定义环境共存
    const allEnvironments = props.project.environments.map(env => ({
      id: env.id,
      type: env.type
    }));
    
    // 使用增强的存储管理方法
    storageManager.addActiveEnvironmentsWithInfo(id, envType, allEnvironments);
  } else {
    // 取消激活环境
    storageManager.deleteActiveEnvironments(id);
  }

  // 更新本地状态
  activeEnvironments.value = storageManager.getActiveEnvironments();
  
  // 通知父组件环境变化
  emit('environmentChange', id, checked, envType);
};

// 编辑项目
const onEdit = () => {
  emit('edit', props.project.id);
};

// 删除项目
const onDelete = async () => {
  try {
    await projectApi.delete(props.project.id);
    message.success('项目删除成功');
    emit('delete', props.project.id);
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};

// 初始化时获取活跃环境
updateActiveEnvironments();
</script>

<style scoped>
.project-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.project-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.project-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.project-group {
  margin-bottom: 16px;
}

.environments-section h4 {
  margin: 16px 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.environments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

/* 自定义滚动条样式 */
.environments-list::-webkit-scrollbar {
  width: 6px;
}

.environments-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.environments-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.environments-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.environment-item {
  padding: 12px;
  border: 1px solid #e6f7ff;
  border-radius: 6px;
  background-color: #f5faff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  transition: all 0.2s ease;
}

.environment-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.environment-name {
  font-weight: 600;
  color: #1890ff;
}

.environment-hosts {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
}

.host-item {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  max-width: 100%;
}

.environment-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 12px;
  color: #1890ff;
  font-weight: 500;
}
</style>
